//获取应用实例
let app = getApp();
let httptool=require("../../utils/zry.httptool.js");
let tabjs = require("../../utils/tab.js");
Page({
  data:{
    radioCheckVal:'',
    tabNum:'',
    selectCircle:true,
    selectArea:false,
    ImgList:[],
    selfcircleList:[],//自建盟圈数据
    forum:{},//圈子列表展示数据
    Titile:'',//title输入框内容
    evaContent:'',//文本域描述内容   
    needuploadcount:0,
    uploadcount:0,
    CircleId:0,
    shareLocal:'本市擂盟',
    params:{},//重新编辑时获取帖子内容的参数
    forumTopic:{},//帖子数据
    delimg:true,//是否显示删除按钮
    circleChoose:false,//发帖选择擂盟的区域
    resendArea:true,//重新发帖时选择擂盟的展示
    sendaddr:'',
    etype:0,//是编辑还是重新发帖
    shareId:'',//是分享还是编辑
    BottomId:'',//局ID
    BoxRecordId:'',//回合ID
    RecordShared:{},//分享的成绩列表
    ID:'',//打擂的成绩ID
    msgprop:'',//消息提示  
  },
  postTitle:function(e){
    let Titile=e.detail.value;
    this.setData({Titile:Titile});
  },
  charChange:function(e){//文本域值的获取
    this.setData({evaContent:e.detail.value});
    console.log(e.detail.value);
  },
  clearinput:function(e){
    let that=this; 
    that.setData({Titile:''});
  },
  clearCont:function(e){//清除输入的内容
    let that=this; 
    that.setData({evaContent:''});
  },
  delImgwall:function(e){
    let that=this;
    let v = e.currentTarget.dataset.idx;
    let ImgList=that.data.ImgList;
    ImgList.splice(v, 1);
    that.setData({ImgList: ImgList});
  },
  tabClick:function(e){//发布擂盟选择
    let that=this;
    let num=e.currentTarget.dataset.num;
    console.log(num);
    that.setData({ tabNum: num, CircleId: 0, radioCheckVal:''});
    if(num=="1"){
      that.setData({CircleId:1});
    }
    if(num=="2"){
      that.setData({CircleId:app.getStorage('cityId')});
    }
    if(num=="3"){
        let selectCircle = this.data.selectCircle;
        if(selectCircle == true){
            this.setData({ selectArea:true, selectCircle:false });
        }else{
          this.setData({ selectArea:false, selectCircle:true });
        }
    }else{
        this.setData({ selectArea:false, selectCircle:true });
    }
  },
  radioCheckedChange: function (e) {
    console.log( e.detail.value);
    this.setData({ radioCheckVal: e.detail.value, CircleId:e.detail.value });
  },
  addImg:function(e){
    var that = this;  
    var imgcount=that.data.ImgList.length;
    wx.chooseImage({
      count: 9 - imgcount, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res){
        for (let i= 0; i < res.tempFilePaths.length;i++){
          that.data.ImgList.push(res.tempFilePaths[i]); 
        }  
        that.setData({ forum: that.data.forum,ImgList: that.data.ImgList});
      }
    });
  },
  upload: function (i){
    let self=this;
    let ImgList = self.data.ImgList;
    if (ImgList[i].indexOf("http://tmp") == 0 || ImgList[i].indexOf("wxfile://") == 0)
    {
      let filepath = self.data.ImgList[i];
      let rootUrl = httptool.getRootUrl();
      let myDate = new Date();
      wx.uploadFile({
        url: rootUrl + 'api/ImgUpload/ImgUploadAsync', //开发者服务器 url
        filePath: filepath,//要上传文件资源的路径
        name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
        formData: { //HTTP 请求中其他额外的 form data
          savepath: "File\\forum\\",
          token: "62ccad6d-9611-41c5-96f6-08ec0ada0f68",
          time: myDate.getMilliseconds()
        },
        success: function (res) {
         var data = JSON.parse(res.data);
         if (data.suc) {
           self.data.ImgList[i] = rootUrl + data.data;
           self.setData({ ImgList: self.data.ImgList });
           if (i == ImgList.length-1){
             self.updatecustomer(self);
           }else{
             i++;
             self.upload(i);
           }
         }
        }, fail(res) {
           wx.hideLoading();
        }
     })
    }
    else if (ImgList.length-1>i){
      i++;
      self.upload(i);
    }
    else{
      self.updatecustomer(self);
    }    
  },
  sendPost:function(e){
    let that=this;
    if (that.data.Titile == '') {
      app.showNotify(that, "帖子名称不能为空！");
      return false;
    } else if (that.data.evaContent == '') {
      app.showNotify(that, "帖子内容不能为空！");
      return false;
    }
    else if (that.data.CircleId == 0 && that.data.etype != 1) {
      app.showNotify(that, "请选择擂盟！");
      return false;
    }
    app.showLoading({ title: "图片上传中" });
    let imglist = that.data.ImgList;
    if(imglist.length>0){
      that.upload(0);
    }else{
      that.updatecustomer(that);
    }    
  },
  updatecustomer:function(that){
    if (that.data.etype == 1) {//重新编辑
      that.editTopic(that);
    } else {
      that.addTopic(that);
    }
  },
  addTopic: function (that){    
    if (that.data.shareId == 1){//分享（带成绩）
      that.data.forum.BottomId = that.data.BottomId;
      that.data.forum.BoxRecordId = that.data.BoxRecordId;
    }
    else {//发帖（没有成绩）
      that.data.forum.BoxRecordId = 0;
      that.data.forum.BottomId = 0;
    }
    that.data.forum.Content = that.data.evaContent;
    that.data.forum.Titile = that.data.Titile;
    that.data.forum.CreateBy = app.getStorage('customerId');
    that.data.forum.CircleId = that.data.CircleId;
    that.data.forum.TopicType = that.data.tabNum;
    that.data.forum.ImgList = that.data.ImgList;    
    
    if (that.data.forum.Content != '' && that.data.forum.Titile != '') {
      httptool.ajaxPost("api/Topic/AddTopic", that.data.forum, function (res) {//发帖
        if (res.suc) {
          wx.navigateBack(); 
        } else {
           app.showNotify(that, res.msg);
        }
        wx.hideLoading();  
      }, function () { wx.hideLoading();  });
    }
  },
  editTopic: function (that) {//重新编辑发帖
    that.data.forum.UserId = app.getStorage('customerId');
    that.data.forum.Content = that.data.evaContent;
    that.data.forum.Titile = that.data.Titile;
    that.data.forum.ID = that.data.params.ID;
    that.data.forum.ImgList = that.data.ImgList;
    httptool.ajaxPost("api/Topic/UpdateTopic", that.data.forum, function (res) {
      if (res.suc) {
        wx.navigateBack(); 
      } else {
        app.showNotify(that, res.msg);
      }
      wx.hideLoading();
    }, function () { wx.hideLoading(); });
  },
  onLoad: function (options) {
    let that = this;
    httptool.login(function () {
      // 页面初始化 options为页面跳转所带来的参数
      let params={};
      let etype=options.etype;//1：重新编辑，2：发帖，3：分享
      let shareId=options.shareId;//区分是分享还是还是发帖
      let BottomId=options.BottomId;//局ID
      let BoxRecordId=options.BoxRecordId;//回合ID
      let ID=options.ID;//成绩ID
      params.ID=options.topicId;//跳转过来带的帖子ID
      params.UserId=app.getStorage('customerId');
      that.setData({params:params});
      let CircleName=app.getStorage('CircleName');
      if(etype==1){
        that.setData({delimg:false,circleChoose:true,resendArea:false});
        wx.setNavigationBarTitle({
          title: '重新编辑'
        })
        that.getTopicDetail();
      }
      that.setData({shareLocal:CircleName,etype:etype,shareId:shareId,BottomId:BottomId,
      BoxRecordId:BoxRecordId,ID:ID});
      that.getMyCircle(); 
      if(shareId==1){
        wx.setNavigationBarTitle({
          title: '分享'
        });
        that.GetBoxRecordShared();
      }
    });
  },
  getMyCircle:function(){
    let that = this;
    /**获取自建盟列表选择的数据**/
    let customerId = app.getStorage('customerId');
    httptool.ajaxPost("api/Circle/GetMyCircle", { UserId: customerId }, function (res) {//获取自建擂盟的数据
      if (res.suc) {
        if (res.data != "" && res.data != null && res.data != undefined) {
          let data = res.data;
          if (data.DataList.length > 0) {
            that.setData({ selfcircleList: data.DataList });
          }
        }
      } else {
         app.showNotify(that, res.msg);
      }
    });
  },
  getTopicDetail:function(e){//获取帖子详情的内容
    let that=this;
    let selfcircleList=that.data.selfcircleList;
    httptool.ajaxPost("api/Topic/GetTopicDetail",that.data.params,function(res){
      if(res.suc){
          let datas=res.data;
          if(datas!=''&& datas!=null && datas!=undefined){
            that.data.forum.Content=datas.Content;
            that.setData({forumTopic:datas,ImgList:datas.ImgList,selectCircle:false});
            that.data.forumTopic.TopicType=datas.TopicType;
            that.setData({Titile:datas.Titile,evaContent:datas.Content});
            if(datas.TopicType==1){
              that.setData({sendaddr:'全国擂盟'});
            }else if(datas.TopicType==2){
              that.setData({sendaddr:that.data.shareLocal});
            }else if(datas.TopicType==3){
              if(selfcircleList.length==0){
                that.setData({sendaddr:'我的萌盟'});
              }else if(selfcircleList.length>0){
                for(let i=0;i<selfcircleList.length;i++){
                  if(that.data.forumTopic.ID==selfcircleList[i].ID){
                      that.setData({sendaddr:selfcircleList[i].Name});
                  }else{
                    that.setData({sendaddr:'我的萌盟'});
                  }
                }
              }
            }
          }
      }else{
         app.showNotify(that, res.msg);
      }
    });
  },
  GetBoxRecordShared:function(){//获取分享的成绩列表
    let that=this;
    httptool.ajaxPost("api/BoxRecord/GetBoxRecordShared", {ID:that.data.ID }, function (res) {
      if (res.suc) {
          let data=res.data.Score;
          that.setData({RecordShared:data});
      } else {
         app.showNotify(that, res.msg);
      }
    });
  }
})